/*
 * @Author: actor
 * @Date: 2023-11-13 15:43:57
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-19 10:11:22
 * @FilePath: \i-hos-app\shared\emr\src\hooks\useCommon.ts
 * @Description: 电子病历页面操作共享方法
 */
// 接口约束
import { IConfig } from '../interface/page'
import { IPageConfigStore } from '../interface/page'

// store数据
import { usePageConfigStore } from '../store/pageConfig'

export const useCommon = (): any => {
  // 解构 store的配置数据
  const configStore: IPageConfigStore = usePageConfigStore()

  // 获取配置的属性
  const getConfig = (flag: string): IConfig | null => {
    if (flag == undefined || !flag) return null
    let config: IConfig = JSON.parse(flag)
    if (!!flag && !!Array.isArray(config.option)) {
      config.option = config.option.join(',').replace(/,/g, '\n')
    }
    return config
  }

  // 设置配置的属性
  const setConfig = (): void => {
    if (configStore.el == '') return
    let curEl = document.getElementById(configStore.el) as HTMLElement
    let flag = configStore.val as IConfig
    if (!!flag && !!Array.isArray(flag.option)) {
      flag.option = flag.option.join(',').replace(/,/g, '\n')
    }
    if (!!curEl) curEl.dataset.config = JSON.stringify(flag)
  }

  // 查找某一个指定元素到指定元素的所有父级元素(通过class或者标签的某个属性； flag：{cls：'',id:'', atr:''})
  // isEmpty 传true，表示咋找不到就不返回指定的元素，返回空
  const findParents = (el: any, flag?: any, isEmpty?: Boolean): any => {
    let _el = el as HTMLElement
    let nodes: any = []
    let bool = (dom: any): any => {
      if (dom) {
        let val: boolean = false
        if (flag.cls) {
          val = !!dom.className?.includes(flag.cls as string)
        } else if (flag.id) {
          val = !!dom.id?.includes(flag.id as string)
        } else {
          val = dom[flag.atr as string] || (dom.dataset != undefined && !!dom.dataset[flag.atr as string])
        }
        return val
      }
    }
    if (el) {
      nodes.push(el)
      if (bool(el)) return nodes
      while (el.parentNode) {
        nodes.unshift(el.parentNode)
        el = el.parentNode
        if (bool(el)) {
          break
        } else if (el.parentNode.nodeName == '#document') {
          nodes = []
          if (isEmpty == undefined || !isEmpty) nodes.push(_el)
          break
        }
      }
    }
    return nodes
  }

  // 元素节点的特殊处理
  const handleHtml = (flag: any, type?: string): any => {
    if (type == 'checkBox' || type == 'checkbox' || type === 'radio') {
      // 处理单复选框的标签属性（组件插入时）
      for (let item of flag) {
        let iInput = item.querySelectorAll('input') as HTMLElement[]
        for (var i = 0; i < iInput.length; i++) {
          let id: string = item.id + '_' + type + '_' + i
          if (iInput[i].nodeName == 'INPUT') {
            iInput[i].id = id
            iInput[i].setAttribute('name', id)
            if (iInput[i].nextElementSibling?.nodeName == 'LABEL') {
              iInput[i].nextElementSibling?.setAttribute('for', id)
            }
          }
        }
      }
    } else {
      let iTarget: any = flag.target
      if (!iTarget || iTarget.className.includes('selectBoxForm')) return

      // 获取指定最近的属性有config的父级元素以及属性type
      let speEl = findParents(iTarget, { atr: 'config' })[0] as HTMLElement
      let type: string = !!speEl.getAttribute('type') ? speEl.getAttribute('type') : iTarget.getAttribute('type')

      if (type == 'checkBox' || type == 'checkbox' || type == 'radio') {
        iTarget = iTarget.nodeName == 'INPUT' || iTarget.nodeName == 'LABEL' ? iTarget : iTarget.querySelector('input')
        // 当前操作input的元素
        let id: string = iTarget.getAttribute('for') ? iTarget.getAttribute('for') : iTarget.getAttribute('id')
        let curIpt = document.getElementById(id) as HTMLInputElement
        let ipt: any = speEl.querySelectorAll('input')
        // 选中的value
        let checkedVal: string[] = []

        // 处理单复选框的状态（页面操作点击时）
        if (type == 'radio') {
          for (let item of ipt) {
            item.checked = false
            item.removeAttribute('checked')
          }
          curIpt.checked = true
        } else {
          if (curIpt.checked) {
            setTimeout(() => {
              curIpt.checked = false
            })
          } else {
            setTimeout(() => {
              curIpt.checked = true
            })
          }
        }
        setTimeout(() => {
          curIpt.checked ? curIpt.setAttribute('checked', 'true') : curIpt.removeAttribute('checked')
          for (let item of ipt) {
            if (item.checked) checkedVal.push(item.value)
          }
          configStore.$patch?.((state: IPageConfigStore) => {
            state.val.textVal = checkedVal.join(',')
          })
        })
      }

      // 返回指定的元素
      return speEl
    }
  }

  return {
    getConfig,
    setConfig,
    handleHtml,
    findParents,
  }
}
